import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

/// Copyright (C), 2021-2023, Franky Lee
/// @ProjectName: kusaiapp
/// @Package:
/// @ClassName: highlight_text
/// @Description:
/// @Author: frankylee
/// @CreateDate: 2023/11/14 15:44
/// @UpdateUser: frankylee
/// @UpdateData: 2023/11/14 15:44
/// @UpdateRemark: 更新说明

typedef OnTapCallback = void Function(String key);

class HighlightText extends StatefulWidget {
  final List<String> data;
  final List<String> keys;
  final TextStyle? style;
  final TextStyle? keyStyle;
  final OnTapCallback? onTapCallback;

  const HighlightText({
    super.key,
    required this.data,
    required this.keys,
    this.style,
    this.keyStyle,
    this.onTapCallback,
  });

  @override
  HighlightTextState createState() => HighlightTextState();
}

class HighlightTextState extends State<HighlightText> {
  @override
  Widget build(BuildContext context) {
    return Text.rich(
      TextSpan(
        style: DefaultTextStyle.of(context).style,
        children: <InlineSpan>[
          ...widget.data.map(
            (e) {
              if (widget.keys.contains(e)) {
                return TextSpan(
                  text: e,
                  style: widget.keyStyle ??
                      TextStyle(
                        color: Theme.of(context).primaryColor,
                      ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      widget.onTapCallback?.call(e);
                    },
                );
              } else {
                return TextSpan(text: e, style: widget.style);
              }
            },
          )
        ],
      ),
    );
  }
}
